package com.weilele.library.download.impl

import com.weilele.library.download.IMvvmDownload
import com.weilele.mvvm.utils.thread.TickTask
import kotlinx.coroutines.CoroutineScope

abstract class BaseMvvmDownload : IMvvmDownload {

    private val listeners = mutableListOf<IMvvmDownload.Listener>()

    //三秒定时刷新一次
    private var tickTask: TickTask? = null

    override fun onCreate() {
        super.onCreate()
        tickTask = TickTask.start(1000, true, ::onTick)
    }

    override fun onDestroy() {
        super.onDestroy()
        tickTask?.onDestroy()
        listeners.clear()
    }

    override fun onStart() {
        super.onStart()
        tickTask?.onStart()
    }

    override fun onStop() {
        super.onStop()
        tickTask?.onStop()
    }

    override fun addListener(listener: IMvvmDownload.Listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    override fun removeListener(listener: IMvvmDownload.Listener) {
        listeners.remove(listener)
    }

    protected fun listenersForEach(action: (IMvvmDownload.Listener) -> Unit) {
        listeners.toList().forEach(action)
    }

    abstract suspend fun onTick(scope: CoroutineScope)
}